from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from pydantic import BaseModel
from typing import List, Dict, Any, Optional
import uuid
from datetime import datetime, timedelta
import json

from database import get_db, ChatHistory, DecisionRule, DataSource, DataRecord
from services.ai_service import ai_service
from services.cache_service import CacheService, CacheKeys

router = APIRouter()

class ChatMessage(BaseModel):
    message: str
    session_id: Optional[str] = None
    decision_rule_id: Optional[int] = None

class ChatResponse(BaseModel):
    session_id: str
    user_message: str
    ai_response: str
    timestamp: str
    decision_rule_id: Optional[int] = None

@router.post("/send", response_model=ChatResponse)
async def send_message(
    chat_message: ChatMessage,
    db: Session = Depends(get_db)
):
    """发送聊天消息"""
    try:
        # 生成或使用会话ID
        session_id = chat_message.session_id or str(uuid.uuid4())
        
        # 获取决策规则（如果指定）
        decision_rule = None
        if chat_message.decision_rule_id:
            decision_rule = db.query(DecisionRule).filter(
                DecisionRule.id == chat_message.decision_rule_id,
                DecisionRule.is_active == True
            ).first()
        
        # 获取相关上下文数据
        context_data = await get_context_data(db, decision_rule)
        
        # 使用AI服务生成回复
        ai_response_data = await ai_service.get_decision_advice(
            user_question=chat_message.message,
            context_data=context_data,
            decision_rule=decision_rule.prompt_template if decision_rule else None
        )
        
        if not ai_response_data["success"]:
            raise HTTPException(status_code=500, detail="AI服务暂时不可用")
        
        ai_response = ai_response_data["advice"]
        
        # 保存对话历史
        chat_history = ChatHistory(
            session_id=session_id,
            user_message=chat_message.message,
            ai_response=ai_response,
            decision_rule_id=chat_message.decision_rule_id
        )
        db.add(chat_history)
        db.commit()
        
        # 缓存会话数据
        cache_key = CacheKeys.chat_session_key(session_id)
        session_data = {
            "session_id": session_id,
            "last_message": chat_message.message,
            "last_response": ai_response,
            "timestamp": datetime.now().isoformat()
        }
        await CacheService.set(cache_key, session_data, expire=3600)
        
        return ChatResponse(
            session_id=session_id,
            user_message=chat_message.message,
            ai_response=ai_response,
            timestamp=datetime.now().isoformat(),
            decision_rule_id=chat_message.decision_rule_id
        )
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理消息失败: {str(e)}")

@router.get("/history/{session_id}")
async def get_chat_history(session_id: str, db: Session = Depends(get_db)):
    """获取聊天历史"""
    try:
        # 从数据库获取历史记录
        history_records = db.query(ChatHistory).filter(
            ChatHistory.session_id == session_id
        ).order_by(ChatHistory.created_at.asc()).all()
        
        history = []
        for record in history_records:
            history.append({
                "id": record.id,
                "user_message": record.user_message,
                "ai_response": record.ai_response,
                "timestamp": record.created_at.isoformat(),
                "decision_rule_id": record.decision_rule_id
            })
        
        return {
            "success": True,
            "session_id": session_id,
            "history": history,
            "total_messages": len(history)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取聊天历史失败: {str(e)}")

@router.get("/sessions")
async def get_active_sessions(db: Session = Depends(get_db)):
    """获取活跃会话列表"""
    try:
        # 获取最近24小时内的会话
        yesterday = datetime.now() - timedelta(days=1)
        recent_sessions = db.query(ChatHistory).filter(
            ChatHistory.created_at >= yesterday
        ).all()
        
        # 按会话分组
        sessions = {}
        for record in recent_sessions:
            if record.session_id not in sessions:
                sessions[record.session_id] = {
                    "session_id": record.session_id,
                    "message_count": 0,
                    "last_message": "",
                    "last_timestamp": "",
                    "decision_rule_id": record.decision_rule_id
                }
            
            sessions[record.session_id]["message_count"] += 1
            if record.created_at.isoformat() > sessions[record.session_id]["last_timestamp"]:
                sessions[record.session_id]["last_message"] = record.user_message
                sessions[record.session_id]["last_timestamp"] = record.created_at.isoformat()
        
        return {
            "success": True,
            "sessions": list(sessions.values()),
            "total_sessions": len(sessions)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取会话列表失败: {str(e)}")

@router.delete("/session/{session_id}")
async def delete_session(session_id: str, db: Session = Depends(get_db)):
    """删除会话"""
    try:
        # 删除数据库中的记录
        deleted_count = db.query(ChatHistory).filter(
            ChatHistory.session_id == session_id
        ).delete()
        
        db.commit()
        
        # 删除缓存
        cache_key = CacheKeys.chat_session_key(session_id)
        await CacheService.delete(cache_key)
        
        return {
            "success": True,
            "session_id": session_id,
            "deleted_messages": deleted_count
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除会话失败: {str(e)}")

async def get_context_data(db: Session, decision_rule: Optional[DecisionRule]) -> Dict[str, Any]:
    """获取上下文数据"""
    context_data = {}
    
    try:
        # 如果指定了决策规则，获取相关数据源
        if decision_rule and decision_rule.data_sources:
            try:
                data_sources = json.loads(decision_rule.data_sources)
                for source_type in data_sources:
                    # 获取该类型的最新数据
                    source = db.query(DataSource).filter(
                        DataSource.data_type == source_type,
                        DataSource.is_active == True
                    ).first()
                    
                    if source:
                        latest_record = db.query(DataRecord).filter(
                            DataRecord.source_id == source.id
                        ).order_by(DataRecord.timestamp.desc()).first()
                        
                        if latest_record:
                            try:
                                data = json.loads(latest_record.data_json)
                                context_data[source_type] = {
                                    "data": data,
                                    "last_updated": latest_record.timestamp.isoformat(),
                                    "source_name": source.name
                                }
                            except json.JSONDecodeError:
                                continue
            except json.JSONDecodeError:
                pass
        
        # 如果没有指定决策规则或数据源，获取所有活跃数据源的最新数据
        if not context_data:
            data_sources = db.query(DataSource).filter(DataSource.is_active == True).all()
            
            for source in data_sources:
                latest_record = db.query(DataRecord).filter(
                    DataRecord.source_id == source.id
                ).order_by(DataRecord.timestamp.desc()).first()
                
                if latest_record:
                    try:
                        data = json.loads(latest_record.data_json)
                        context_data[source.data_type] = {
                            "data": data,
                            "last_updated": latest_record.timestamp.isoformat(),
                            "source_name": source.name
                        }
                    except json.JSONDecodeError:
                        continue
        
        return context_data
        
    except Exception as e:
        print(f"获取上下文数据失败: {e}")
        return {}
